package cloud.maque.auth.github.controller;

import cloud.maque.auth.common.CommnCallBack;
import cloud.maque.auth.conf.AuthProperties;
import cloud.maque.auth.model.LoginResponse;
import cloud.maque.common.core.enums.LoginType;
import cloud.maque.common.core.response.R;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;

@RestController
@RequestMapping("/auth")
public class GithubController {


    @Autowired
    AuthProperties authProperties;

    @Autowired
    CommnCallBack commnCallBack;


    /**
     * Gitee 跳转地址
     * https://gitee.com/oauth/authorize?client_id=45b843a4a87fdc577f12c75aae3caf0664d45d02ff16fabccd9d57d9eaeac33c&redirect_uri=http%3A%2F%2Flocalhost%3A9002%2Fauth%2Fcallback%2Fgitee&response_type=code&state=1
     *
     * @param Coupled 是否前后端分离，1是，其它为否
     */
    @RequestMapping("/authorize/github")
    public void JumpToGitee(@RequestParam("Coupled") String Coupled) throws IOException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        String url = authProperties.getGithub().GetFullUrl(authProperties.getGithub(), Coupled);
        response.sendRedirect(url);
    }

    /**
     * Gitee 回调地址
     *
     * @param code
     * @param state 是否是ajax
     * @return
     */
    @RequestMapping("/callback/github")
    public R<LoginResponse> GithubCallBack(@RequestParam("code") String code, @RequestParam(name = "state", required = false) String state) throws IOException {

        return commnCallBack.CallBack(code, state, LoginType.GITHUB);
    }

}
